import urllib.request
import os
import urllib.error

def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER')
    req.add_header('Referer','http://cl.uuxpy.com/index.php')
    response = urllib.request.urlopen(req)
    html = response.read()

    return html

def get_page(url):

    count = 5
    page_addrs = []

    html = open_url(url).decode('utf-8')

    c = html.find('href=')

    while count > 0:
        d = html.find('.',c)
        page_addrs.append(html[c+23:d])
        c = html.find('href=',d)
        count  = count - 1
        

    return page_addrs
                          
def find_imgs(url):
    html = open_url(url).decode('utf-8')
    img_addrs = []

    a = html.find('src=')

    while a!=-1:
        b = html.find('.jpeg',a,a+255)

        if b != -1:
            img_addrs.append(html[a+5:b+5])
        else:
            b = a + 5

        a = html.find('src=',b)

    return img_addrs

def save_imgs(folder,img_addrs):
    for each in img_addrs:
        filename = each.split('/')[-1]
        with open(filename,'wb') as f:
            img = open_url(each)
            f.write(img)




def download_mm(folder='OOXX'):
    os.mkdir(folder)
    os.chdir(folder)

    url = 'http://cl.uuxpy.com/thread0806.php?fid=16'
    page_num = get_page(url)

    try:
        for each in page_num:
            page_url = 'http://cl.uuxpy.com/htm_data/16/1609/' + each + '.html'
            img_addrs = find_imgs(page_url)
            save_imgs(folder,img_addrs)

    except urllib.error.URLError as e:
                   if hasattr(e,'reason'):
                       print('Reason:',e.reason)
                   elif hasattr(e,'code'):
                       print('Code:',e.code)
    else:
        print('OK')
                   
if __name__ == '__main__':
    download_mm()
